package com.example.mychess;

import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class Sever {
    static SQL root;

    static {
        try {
            root = new SQL();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static Map<Integer, ServerThread> clients;//保存登录的所有客户端线程
    private static Map<Integer,String> red=new HashMap<Integer, String>();
    private static Map<Integer,String> black=new HashMap<>();
    private static int[] a={0,0,0,0,0,0,0,0,0,0};
    public static void main(String[] args) {
        start();
    }
    public static void SEVER(){
        FXMLLoader fxmlLoader = new FXMLLoader(Sever.class.getResource("user-sever.fxml"));
        Scene scene = null;
        try {
            scene = new Scene(fxmlLoader.load(), 600, 500);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Stage s = new Stage();
        s.setTitle("用户管理");
        s.setScene(scene);
        s.show();
    }
    public static void start() {
        try {
            int i=0;
            AtomicInteger j= new AtomicInteger();
            j.set(0);
            clients = new HashMap<>();
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("服务器启动");
            while (true) {
                Socket socket = serverSocket.accept();
                ServerThread serverThread = new ServerThread(socket);
                clients.forEach((k, v) -> {
                    if(v.getSocket()==socket){
                        j.set(1);
                    }
                });
                if(j.get() ==0){
                clients.put(i++,serverThread);}
                serverThread.start();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static class ServerThread extends Thread {
        private Socket socket;

        public Socket getSocket() {
            return socket;
        }

        public void setSocket(Socket socket) {
            this.socket = socket;
        }

        public ServerThread(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            while (true) {
                Object receive=SocketUtil.receive(socket);
                System.out.println(((Message)receive).getType());
                if (receive instanceof Message){
                    Message message = (Message) receive;
                    switch (message.getType()) {
                        case LOGIN -> {
                            try {
                                login(message);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        case JOIN -> {
                            Join(message);
                        }
                        case FIGHT -> {
                            fight(message);
                        }
                        case REG -> {
                            reg(message);
                        }
                        case MOVE -> {
                            move(message);
                        }
                        case UPDATE_SUCCESS -> {
                            try {
                                US(message);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        case UPDATE_FAILURE -> {
                            try {
                                UF(message);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        case LEAVE -> {
                            try {
                                leave(message);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        case A -> {
                            try {
                                a(message);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        case ZHUCE -> {
                            try {
                                zhuce(message);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        default -> System.out.println("未知的消息");
                    }
                }
//                SocketUtil.send(socket, "登陆成功");
            }
        }

        private void zhuce(Message message) throws SQLException {
            Message response = new Message();
            int i=0;
            for (User user : root.findAll()){
                if (user.getAccount().equals(message.getUser().getAccount())){
                    System.out.println(user.getAccount());
                    i=1;
                    response.setType(Message.Type.ZHUCE_FAILURE);
                    clients.forEach((k, v) -> {
                        SocketUtil.send(v.getSocket(), response);
                    });
                }
            }
            if(i==0){
                message.getUser().setIntegral(0);
                message.getUser().setSex("男");
                message.getUser().setPsst("不在线");
            root.insert(message.getUser());
            response.setType(Message.Type.ZHUCE);
            clients.forEach((k, v) -> {
                SocketUtil.send(v.getSocket(), response);
            });}
            System.out.println(i);
        }

        private void a(Message message) throws SQLException {
            for (User user : root.findAll()){
                if (user.getAccount().equals(message.getFrom())){
                    Message response = new Message();
                    Message msg=new Message();
                    msg.setA(a);
                    msg.setType(Message.Type.A);
                    msg.setUser(user);
                    clients.forEach((k, v) -> {
                        SocketUtil.send(v.getSocket(), msg);
                    });
                    return;
                }
            }

        }

        private void leave(Message message) throws SQLException {
            for (User user : root.findAll()){
                if (user.getAccount().equals(message.getFrom())){
                    user.setPsst("不在线");
                    root.update(user);
                }
            }
        }

        private void UF(Message message) throws SQLException {
            for (User user : root.findAll()){
                if (user.getAccount().equals(message.getFrom())){
                    user.setIntegral(user.getIntegral()-2);
                    root.update(user);
                }
            }
        }

        private void US(Message message) throws SQLException {
            for (User user : root.findAll()){
                if (user.getAccount().equals(message.getFrom())){
                    user.setIntegral(user.getIntegral()+2);
                    root.update(user);
                }
            }
        }

        private void fight(Message message) {
            black.put(message.getTable(),message.getFrom());
            Message response = new Message();
            response.setType(Message.Type.FIGHT);
            response.setTo(red.get(message.getTable()));
            response.setA(a);
            response.setContent("加入成功");
            clients.forEach((k, v) -> {
                if(response.getType()==Message.Type.FIGHT){
                    a[message.getTable()-1]=2;
                    SocketUtil.send(v.getSocket(), response);
                }

            });
            System.out.println("fight success");
        }

        private void Join(Message message) {

            red.put(message.getTable(),message.getFrom());
            Message response = new Message();
            response.setType(Message.Type.SUCCESS);
            response.setA(a);
            response.setContent("进入成功");
            clients.forEach((k, v) -> {
                if(response.getType()==Message.Type.SUCCESS){
                    a[message.getTable()-1]=1;
                SocketUtil.send(v.getSocket(), response);}
            });
        }

        private void move(Message message) {
            clients.forEach((k, v) -> {
                SocketUtil.send(v.getSocket(), message);
            });
        }

        private void reg(Message message) {
        }

        private void login(Message message) throws SQLException {
            for (User user : root.findAll()){
                if (user.getAccount().equals(message.getFrom())&&user.getPassword().equals(message.getFrompassword())&&user.getPsst().equals("不在线")){
                    user.setPsst("在线");
                    root.update(user);
                    Message response = new Message();
                    response.setType(Message.Type.SUCCESS);
                    response.setContent("登陆成功");
                    response.setA(a);
                    response.setUser(user);
                    SocketUtil.send(socket, response);
                    return;
                }
            }
            Message response = new Message();
            response.setType(Message.Type.FAILURE);
            response.setContent("登陆失败");
            SocketUtil.send(socket, response);
        }
    }
}
